package me.luck2.wicketcaptcha;

import java.awt.Dimension;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.extensions.captcha.kittens.KittenCaptchaPanel;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HomePage extends WebPage {
	Logger logger = LoggerFactory.getLogger(HomePage.class);

	private final KittenCaptchaPanel captcha;
	private int errors;

	/**
	 * Constructor that is invoked when page is invoked without a session.
	 * 
	 * @param parameters
	 *            Page parameters
	 */
	public HomePage(final PageParameters parameters) {
		add(captcha = new KittenCaptchaPanel("captcha", new Dimension(400, 200)));

		// In a real application, you'd check the kittens in a form
		add(new AjaxLink("checkKittens") {

			@Override
			public void onClick(final AjaxRequestTarget target) {
				if (!isSpamBot() && captcha.allKittensSelected()) {
					target.appendJavaScript("alert('you win! happy kittens!');");
				} else {
					errors++;
					if (isSpamBot()) {
						target.appendJavaScript("alert('spammer alert');");
					} else {
						target.appendJavaScript("alert('please try again');");
					}
					target.add(captcha);
				}
				captcha.reset();
			}
		});
	}

	/**
	 * 
	 * @return
	 */
	boolean isSpamBot() {
		return errors > 3;
	}
}